﻿using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using System.ServiceManager.Facade;
using System.ServiceManager.Facade.EnterpriseManagementObjects;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Windows.Media.Imaging;
using Microsoft.EnterpriseManagement.ConsoleFramework;
using Microsoft.EnterpriseManagement.UI.SdkDataAccess;
using MessageBox = System.Windows.Forms.MessageBox;

namespace ServiceManager.TFSIntegration
{
    public class CreateTFSBugCommand : ConsoleCommand
    {
        const string Caption = "Service Manager : Create Bug";

      
        private static void ShowMessage(string message)
        {
            MessageBox.Show(message, Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        
        public override void ExecuteCommand(IList<NavigationModelNodeBase> nodes, NavigationModelNodeTask task,ICollection<string> parameters)
        {

            ConfigureTraceListener();

            var id = string.Empty;
            var title = string.Empty;
            var description = string.Empty;
            
            if (nodes.Count > 1)
            {
                ShowMessage("You cannot choose multiple incidents");
                Trace.TraceError("Multiple incidents were selected");
                return;
            }
            if (nodes.Count == 0)
            {
                ShowMessage("Please select an incident");
                return;
            }
            
            foreach (var node in nodes)
            {
                id = node["$Id$"].ToString();
                break;
            }

             System_WorkItem_Incident incident = null;

            try
            {
                incident = System_WorkItem_Incident.Retrieve(new Guid(id));
            }
            catch(Exception e)
            {
                ShowMessage("Could not retrieve the incident " + id);
                var errmsg = string.Format("Could not retrieve the incident {0} : {1}{2}{1}{3}", id, Environment.NewLine,
                                           e.Message, e.StackTrace);
                Trace.TraceError(errmsg);
                return;
            }
            
            if (incident == null)
            {
                ShowMessage("Could not retrieve the incident " + id);
                return;
            }

            Trace.TraceInformation("Retrieved incident {0}",id);

            var status = incident.Status;
            
            var mp = SCSMServer.GetManagementPack(new Guid("dd26c521-7c2d-58c0-0980-dac2dacb0900"));

            if (status != mp.GetEnumeration("IncidentStatusEnum.Active") )
            {
                ShowMessage("A bug cannot be created by a ticket that is not active");
                 
                return;
            }
            
            if (String.IsNullOrEmpty(incident.Title))
            {
                title = incident.Title;
            }
            else
            {
                ShowMessage("You must have a title");
                return;
            }

            if (String.IsNullOrEmpty(incident.Description))
            {
                description = incident.Description;
            }
            else
            {
                ShowMessage("You must have a description");
                return;
            }
            
            TFSBugData data = null;
            try
            {
                data = new TFSBugData(id,title, description);  
            }
            catch (Exception e)
            {
                ShowMessage("Please configure the Admin settings");
                
                var errmsg = string.Format("Admin settings were not configured {0} : {1}{2}{1}{3}", id, Environment.NewLine,
                                           e.Message, e.StackTrace);
             
                Trace.TraceError( errmsg);
                return;
            }
            var window = GetWindow(data);
            window.ShowDialog();
            if (window.DialogResult.HasValue && window.DialogResult.Value)
            {
                var bugId = TFSService.CreateBug(data);
                UpdateIncident(bugId,incident);
                RequestViewRefresh();
            }
            Trace.Flush();
            Trace.Close();
        }

        private static CreateBugWindow GetWindow(TFSBugData data)
        {
            var window = new CreateBugWindow(data)
                             {
                                 Height = 450,
                                 Width = 450,
                                 WindowStartupLocation = WindowStartupLocation.CenterScreen
                             };

            ElementHost.EnableModelessKeyboardInterop(window);
            
            var stream = new MemoryStream();
            Properties.Resources.bug.Save(stream);
            stream.Seek(0, SeekOrigin.Begin);
            window.Icon = BitmapFrame.Create(stream);
            window.Title = Caption;
            return window;
        }

        private static void UpdateIncident(int id, System_WorkItem_Incident incident)
        {
            incident.TFSBugId = id;
            incident.TFSBugCreated = true;
            incident.Overwrite();
        }

        private static void ConfigureTraceListener()
        {
            var fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                        "SCSMTFSIntegration.log");
            var listener = new TextWriterTraceListener(fileName);         

            // Add the event log trace listener to the collection.
            Trace.Listeners.Add(listener);
        }
    }
    
}